package com.lpf.demo;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.python.core.Py;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import static com.lpf.util.CodeUtils.decodeUTF8Str;

public class DemoPython04 {

    public static void main(String[] args) throws InterruptedException {

        String pythonFunc = "E:\\IdeaProjects\\java-learning\\07-java-python\\src\\main\\resources\\demo\\demoPython04.py";

        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile(pythonFunc);
        PyFunction pyf = interpreter.get("add", PyFunction.class);

        new Thread(() -> {
            PyObject[] pyObjects = new PyObject[1];
            pyObjects[0] = Py.newStringUTF8(JSONUtil.toJsonStr(MapUtil.of("key", "单点01")));
            PyObject Res = pyf.__call__(pyObjects);
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONUtil.parseObj(decodeUTF8Str(Res.toString()));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.out.println(jsonObject);
        }).start();

        Thread.sleep(1000);

        new Thread(() -> {
            PyObject[] pyObjects = new PyObject[1];
            pyObjects[0] = Py.newStringUTF8(JSONUtil.toJsonStr(MapUtil.of("key", "单点02")));
            PyObject Res = pyf.__call__(pyObjects);
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONUtil.parseObj(decodeUTF8Str(Res.toString()));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.out.println(jsonObject);
        }).start();

        interpreter.cleanup();
    }

}